//
//  KATextView.swift
//  kano
//
//  Created by Frank on 2025/5/20.
//

import UIKit
import SnapKit

class KATextView: UIView {

    private var currentCount: UInt = 0
    private var defaultContent: String?
    private var contentChangedNum: Int = 0
    
    var contentPlaceHolder: String = "" {
        didSet {
            textView.setPlaceholder(text: contentPlaceHolder, color: .placeholderColor)
        }
    }
    
    var maxInputLength: Int = 0 {
        didSet {
            updateCountLabel()
        }
    }
    
    var contentText: String = "" {
        didSet {
            textView.placeholderLabel.isHidden = !contentText.isEmpty
            if contentChangedNum == 0 {
                defaultContent = contentText
            }
            textView.text = contentText
            currentCount = UInt(textView.text.count)
            updateCountLabel()
            inputTextComplete?(contentText)
        }
    }
    
    var inputTextComplete: ((String) -> Void)?
    
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.backgroundColor = .backgroundGray
        tv.font = .systemFont(ofSize: 16)
        tv.textColor = .secondaryText
        tv.delegate = self
        tv.isUserInteractionEnabled = false
        tv.layer.cornerRadius = 8
        tv.layer.borderWidth = 1
        tv.layer.borderColor = UIColor.secondaryText.cgColor
        return tv
    }()
    
    private(set) lazy var countLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16)
        label.textColor = .primaryText
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubViews()
        setupNotifications()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupSubViews()
        setupNotifications()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        textView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(kscale(20))
            make.right.equalToSuperview().offset(kscale(-20))
            make.top.equalToSuperview().offset(kscale(6))
            make.bottom.equalToSuperview().offset(kscale(-6))
        }
        
        countLabel.snp.makeConstraints { make in
            make.right.bottom.equalToSuperview()
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let inputView = KAKeyboardInputView()
        inputView.title = "Other reason"
        inputView.contentPlaceHolder = "Please enter the reason for giving up."
        inputView.maxInputLength = 200
        inputView.contentText = contentText
        inputView.show()
        
        inputView.inputTextEndBlock = { [weak self] value in
            self?.contentText = value
        }
    }
}

private extension KATextView {
    func setupSubViews() {
        backgroundColor = .clear
        addSubview(textView)
        addSubview(countLabel)
    }
    
    func setupNotifications() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillShow(_:)),
            name: UIResponder.keyboardWillShowNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardDidHidden(_:)),
            name: UIResponder.keyboardWillHideNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(textChanged(_:)),
            name: UITextView.textDidChangeNotification,
            object: textView
        )
    }
    
    func updateCountLabel() {
        let count = textView.text.count
        let (formattedText, shouldTruncate) = formatTextCount(current: count, total: maxInputLength)
        
        if shouldTruncate {
            textView.text = String(textView.text.prefix(maxInputLength))
        }
        
        countLabel.text = formattedText
        countLabel.textColor = shouldTruncate ? .warningRed : .primaryText
    }
    
    func formatTextCount(current: Int, total: Int) -> (String, Bool) {
        guard total > 0 else { return ("", false) }
        
        let actualCount = min(current, total)
        let shouldTruncate = current > total
        
        return ("\(actualCount)/\(total)", shouldTruncate)
    }
}

// MARK: - notification
extension KATextView {
    @objc func keyboardWillShow(_ notification: Notification) {
        
    }
    
    @objc func keyboardDidHidden(_ notification: Notification) {
       
    }
    
    @objc func textChanged(_ notification: Notification) {
        updateCountLabel()
    }
}

// MARK: - UITextViewDelegate
extension KATextView: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        contentChangedNum += 1
        currentCount = UInt(textView.text.count)
        updateCountLabel()
    }
}


extension UIColor {
    static let backgroundGray = UIColor.ka_hexString("#F4F6FB")
    static let primaryText = UIColor.ka_hexString("#30323E")
    static let secondaryText = UIColor.ka_hexString("#8E93A1")
    static let warningRed = UIColor.red
    static let placeholderColor = UIColor.ka_hexString("#CCCCCC")
}


